﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MedManager.Model;
using Maticsoft.DBUtility;

namespace MedManager
{
    public partial class StockOut : Form
    {
        public StockOut()
        {
            InitializeComponent();
        }

        private DataSet ds;
        private string drugName;

        private void InitControl()
        {
            //TODO
            this.Text = "开药";
            txtDrugName.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            txtDrugName.AutoCompleteSource = AutoCompleteSource.CustomSource;
            //medInfoEntity
            List<medInfoEntity> list = Src.Func.medInfoBll.GetModelList("");
            foreach (medInfoEntity entity in list)
            {
                txtDrugName.AutoCompleteCustomSource.Add(entity.name);
            }
        }

        private void Clear()
        {
            txtDrugName.Text = "";
            txtDrugID.Text = "";
            txtAmount.Text = "";
            txtPrice.Text = "";
            txtLast.Text = "";
            txtTotalPrice.Text = "";
            drugName = "";
        }

        private bool CheckInput()
        {
            bool flag = true;
            if (String.IsNullOrEmpty(txtDrugName.Text))
            {
                flag = false;
                MessageBox.Show(this, "药品名称不能为空！");
                txtDrugName.Focus();
            }
            else if (String.IsNullOrEmpty(txtAmount.Text))
            {
                flag = false;
                MessageBox.Show(this, "药品数量不能为空！");
                txtAmount.Focus();
            }
            return flag;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void StockOut_Load(object sender, EventArgs e)
        {
            InitControl();
        }

        private void txtDrugName_Leave(object sender, EventArgs e)
        {
            //ToDO
            if (!String.IsNullOrEmpty(txtDrugName.Text))
            {
                string sql = "select * from medInfo where name=@name";
                SqlParameter[] sqlParameters = new SqlParameter[1];
                sqlParameters[0] = new SqlParameter("@name", txtDrugName.Text);
                ds = DbHelperSQL.Query(sql, sqlParameters);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    txtDrugID.Text = ds.Tables[0].Rows[0]["id"].ToString();
                    txtPrice.Text = ds.Tables[0].Rows[0]["price"].ToString();
                    txtLast.Text = ds.Tables[0].Rows[0]["inventory"].ToString();
                }
                drugName = txtDrugName.Text;
            }
        }

        private void txtAmount_Leave(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(txtAmount.Text))
            {
                //TODO
            }
        }

        private void txtAmount_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = false;
            if (e.KeyChar >= '0' && e.KeyChar <= '9')
            {
                try
                {
                    long amount = Convert.ToInt64(txtAmount.Text + e.KeyChar);
                    if (amount > Convert.ToInt64(txtLast.Text))
                    {
                        e.Handled = true;
                    }
                    else
                    {
                        e.Handled = false;
                    }
                }
                catch (Exception ex)
                {
                    e.Handled = true;
                }

            }
            else if (e.KeyChar == 8)
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }

        private void txtAmount_KeyUp(object sender, KeyEventArgs e)
        {
            if (!String.IsNullOrEmpty(txtAmount.Text) && !String.IsNullOrEmpty(txtPrice.Text))
            {
                long amount = Convert.ToInt64(txtAmount.Text);
                Decimal price = Convert.ToDecimal(txtPrice.Text);
                txtTotalPrice.Text = (amount * price).ToString();
            }
            else
            {
                txtTotalPrice.Text = "";
            }

        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            Clear();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (CheckInput() == true)
            {


                StringBuilder sql = new StringBuilder();
                SqlParameter[] par;
                CommandInfo commandInfo;
                stockoutEntity stockOut = new stockoutEntity();
                stockOut.medid = Convert.ToInt32(txtDrugID.Text);
                stockOut.priceout = Convert.ToDecimal(txtPrice.Text);
                stockOut.amount = Convert.ToInt64(txtAmount.Text);
                stockOut.importer = Src.Func.user.id;
                List<CommandInfo> list = new List<CommandInfo>();

                //插入
                commandInfo = new CommandInfo();
                sql.Append("insert into stockout");
                sql.Append(" (medid,amount,priceout,importer)");
                sql.Append(" values(@medid,@amount,@priceout,@importer)");
                commandInfo.CommandText = sql.ToString();
                par = new SqlParameter[4];
                par[0] = new SqlParameter("@medid", stockOut.medid);
                par[1] = new SqlParameter("@amount", stockOut.amount);
                par[2] = new SqlParameter("@priceout", stockOut.priceout);
                par[3] = new SqlParameter("@importer", stockOut.importer);
                commandInfo.Parameters = par;
                list.Add(commandInfo);

                //update
                commandInfo = new CommandInfo();
                sql = new StringBuilder();
                sql.Append("update medInfo set inventory=inventory-@amount where id=@id");
                commandInfo.CommandText = sql.ToString();
                par = new SqlParameter[2];
                par[0] = new SqlParameter("@amount", stockOut.amount);
                par[1] = new SqlParameter("@id", stockOut.medid);
                commandInfo.Parameters = par;
                list.Add(commandInfo);

                //select
                //commandInfo=new CommandInfo();
                sql = new StringBuilder("select * from stockin where status=0 and lastamount>0 and medid=@medid");
                par = new SqlParameter[1];
                par[0] = new SqlParameter("@medid", stockOut.medid);
                DataTable dt = DbHelperSQL.Query(sql.ToString(), par).Tables[0];
                long amount1 = stockOut.amount;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    long last = Convert.ToInt64(dt.Rows[i]["lastamount"]);
                    if (last >= amount1)
                    {
                        commandInfo = new CommandInfo();
                        sql = new StringBuilder("update stockin set lastamount=lastamount-@amount where id=@id");
                        par = new SqlParameter[2];
                        par[0] = new SqlParameter("@amount", amount1);
                        par[1] = new SqlParameter("@id", dt.Rows[i]["id"]);
                        commandInfo.CommandText = sql.ToString();
                        commandInfo.Parameters = par;
                        list.Add(commandInfo);
                        break;
                    }
                    else
                    {
                        commandInfo = new CommandInfo();
                        sql = new StringBuilder("update stockin set lastamount=lastamount-@amount where id=@id");
                        par = new SqlParameter[2];
                        par[0] = new SqlParameter("@amount", last);
                        par[1] = new SqlParameter("@id", dt.Rows[i]["id"]);
                        commandInfo.CommandText = sql.ToString();
                        commandInfo.Parameters = par;
                        list.Add(commandInfo);
                        amount1 = amount1 - last;
                    }
                }

                int result = DbHelperSQL.ExecuteSqlTran(list);
                if (result != 0)
                {
                    MessageBox.Show("开药成功！");
                    Clear();
                }
                else
                {
                    MessageBox.Show("失败！");
                }
            }

        }

        private void txtDrugName_TextChanged(object sender, EventArgs e)
        {
            //Clear();
        }




        private void txtDrugName_KeyUp(object sender, KeyEventArgs e)
        {
            if (!String.IsNullOrEmpty(drugName) && !txtDrugName.Text.Trim().Equals(drugName))
            {
                txtDrugID.Text = "";
                txtAmount.Text = "";
                txtPrice.Text = "";
                txtLast.Text = "";
                txtTotalPrice.Text = "";
            }
        }
    }
}
